import os
import base64
import threading
from adapter import MarkDownAdapter
from vuepressUtil import *

class VuePress(MarkDownAdapter):
    def __init__(self,time:str,head:dict):
        self.date,self.time = time.split('_')
        self.time = self.time.replace(':','_')
        self.create_time:str = time
        self.head = head
        self.images:list[str] = []
        self.defects:list[list[str]] = []
        pass
    def push(self,seq:int,src:str,det:str,defects:list[str]):
        n = str(seq)
        p = "/"+self.create_time+"/"
        
        folder = get_image_dir(self.create_time)
        if not os.path.exists(folder):
            os.mkdir(folder)
        # write to vuepress instandly
        save_image(os.path.join(folder,n+".jpg"),base64.b64decode(src))
        save_image(os.path.join(folder,n+"_det.jpg"),base64.b64decode(det))
        # two images source and detected
        # ![](/{time}/{n}.jpg)
        self.images.append(markdown_image(n,'jpg',preffix=p)
                    +markdown_image(n+"_det",'jpg',preffix=p))
        print(f"images:{self.images}")
        self.defects.append(defects)
        print(self.defects)

    def submit(self):
        print("filling template")
        # fill template
        md = template(self.time,self.head,
                [defects_group(idx,item) for idx,item in enumerate(self.defects)],
                make_images_group(self.images))
        print(md)

        file = get_save_md(self.date,self.time)
        write_text(file,md)

        # build docs
        save_index(self.date,self.time)
        update_readme(self.create_time.replace('_','/'),f"/mds/{self.date}/{self.time}.md")
        threading.Thread(target=update_website).start()
        # subprocess.Popen("cd ../www/ && yarn docs:build")